import Vue from 'vue'
import Vuex from 'vuex'
import { Config as $C } from '@/common/js/config.js'
import $U from '@/common/js/base.js'
import { Http as $Http } from '@/common/js/http.js'


Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
		showLoginModal: false,
		shareConfig: {},
		spuid: 0,
		role: 'patient',
		docObj: {}, //医生信息
		
		reportobj: {}, //选中报告
		doctorobj: {}, //选中医生
		couponobj: {}, //选中优惠券
		businessobj: {}, //选中机构
		
		url: '', //登录需要返回的地址
		jzkurl:'',//添加就诊卡后的返回地址
		http_img: 'http://cdn.yingpaipay.com', //请求图片头
		
		/** ------ im ------ */
			// Socket连接状态
			IsOpen: false,
			// SocketTask
			SocketTask: false,
			// 是否上线
			IsOnline: false,

			timeoutObj: null, //断线重连
			heartbeatInterval: null, //心跳检测
			
			emojiData: [],

			openOnComTabBarSetTabBarBadge: false,
			openOnComTabBarDocSetTabBarBadge: false,

			// 用户前缀[prefix]：患者端[HZ] 医生端[]
			user:{ //患者端
				prefix: "HZ",
				uid: 0,
				nick: "",//患者nickname 医生name
				avatar: "",//患者headimgurl 医生img
			},
			userDoc:{ //医生端
				prefix: "DT",
				uid: 0,
				nick: "",//患者nickname 医生name
				avatar: "",//患者headimgurl 医生img
			},

			// 当前聊天对象（进入聊天页面获取）
			FromUser:{
				prefix: "",
				uid: 0,
				nick: "",//患者nickname 医生name
				avatar: "",//患者headimgurl 医生img
			},
			ToUser:{
				prefix: "",
				uid: 0,
				nick: "",
				avatar: ""
			},
			// 当前聊天订单
			chatOrderno: '',

			// 所有的用户端聊天会话列表
			chatList:[],
			// 所有的医生端聊天会话列表
			chatDocList:[],
		/** ------ im end ------ */
	},
	mutations: {
		changeShowLoginModal(state, data) {
			state.showLoginModal = data
		},
		setShareConfig(state, data) {
			state.shareConfig = data
		},
		setSpuid(state, data) {
			state.spuid = data
		},
		changeDocObj(state, data) {
			state.docObj = data
		},
		changeRole(state, data) {
			state.role = data
		},
		selectReportobj(state, data) {
			state.reportobj = data
		},
		selectDoctorobj(state, data) {
			state.doctorobj = data
		},
		selectCouponobj(state, data) {
			state.couponobj = data
		},
		selectBusinessobj(state, data) {
			state.businessobj = data
		},
		Onvuexurl(state, data) {
			state.url = data
		},
		Onjzkurl(state, data) {
			state.jzkurl = data
		},
		
		/** ------ im ------ */
			// 创建聊天对象 √
			createToUser(state,e){
				state.FromUser = e.FromUser
				state.ToUser = e.ToUser
				state.chatOrderno = e.orderno
			},
			// 关闭聊天对象 √
			closeToUser(state){
				state.FromUser = {
					prefix: "",
					uid: 0,
					nick: "",
					avatar: "",
				}
				state.ToUser = {
					prefix: "",
					uid: 0,
					nick: "",
					avatar: ""
				}
				state.chatOrderno = ''
			},

			// 存储会话列表 √
			saveChatList(state,{chatList,client}){
				console.log('存储会话列表',chatList,client)
				uni.setStorageSync(client+'_'+state.user.uid,JSON.stringify(chatList))
			},
		/** ------ im end ------ */
	},
	actions: {
		/** ------ im ------ */
			/**
			 * 开启
			 * 		this.$store.dispatch('openSocket')
			 *
			 * 退出登录
			 * 		this.$store.commit('logout')
			 *  	关闭socket
			 *  	this.$store.dispatch('closeSocket')
			 */
			
			// 开启soket √
			openSocket({ state,dispatch }){
				console.log('openSocket',$C.http_static,$C.websocketUrl)
				console.log('state',state)
				// 防止重复连接
				if(state.IsOpen) return
				// 连接
				state.SocketTask = uni.connectSocket({
					url: $C.websocketUrl,
					complete: ()=> {},
					success: (res)=>{
						console.log('发起连接成功 connectSocket=', res);
						
						dispatch('updateSocketLog', {content: '发起连接成功 connectSocket='+JSON.stringify(res), status:1});
					},
					fail: (err)=>{
						console.log('发起连接失败 connectSocket=', err);
						
						dispatch('updateSocketLog', {content: '发起连接失败 connectSocket='+JSON.stringify(err), status:2});
					},
				});
				if (!state.SocketTask) return;
				
				uni.$emit('onImStatus',{
					action: '开启soket',
					code: 'openSocket',
					IsOpen: state.IsOpen,
					SocketTask: state.SocketTask,
					IsOnline: state.IsOnline,
				});
				
				// 监听开启
				state.SocketTask.onOpen(()=>{
					// 将连接状态设为已连接
					console.debug('将连接状态设为已连接', uni.getStorageSync('token'));
					dispatch('updateSocketLog', {content: '连接已开启', status:1});
					
					state.IsOpen = true
					dispatch('startHeartbeat')
					uni.$emit('onImStatus',{
						action: '监听开启',
						code: 'onOpen',
						IsOpen: state.IsOpen,
						SocketTask: state.SocketTask,
						IsOnline: state.IsOnline,
					});
				})
				// 监听关闭
				state.SocketTask.onClose(()=>{
					console.debug('连接已关闭');
					dispatch('updateSocketLog', {content: '连接已关闭', status:2});
					
					state.IsOpen = false;
					state.SocketTask = false;
					
					$Http({
						url: 'imqddebug',
						data: {
							type: '连接已关闭',
							data: state.user?JSON.stringify(state.user):'',
							debugPt: uni.getSystemInfoSync().platform,
							debug: uni.getStorageSync('userInfo'),
						},
						type:'POST',
						load: false,
						noForceLogin: true,
					})
					
					if(state.heartbeatInterval != null){
						clearInterval(state.heartbeatInterval)
						state.heartbeatInterval = null
					}
					
					uni.$emit('onImStatus',{
						action: '监听关闭',
						code: 'onClose',
						IsOpen: state.IsOpen,
						SocketTask: state.SocketTask,
						IsOnline: state.IsOnline,
					});
					
					// 断线重连, 3秒重连一次
					state.timeoutObj = setTimeout(function() {
						dispatch('openSocket');
					}, 3000);
					
					if(!state.IsOnline){ //用户未登陆
						// if(state.timeoutObj){
						// 	clearTimeout(state.timeoutObj)
						// 	state.timeoutObj = null
						// }

						dispatch('clearLogin')
					}
				})
				// 监听错误
				state.SocketTask.onError((err)=>{
					console.debug('连接错误', err);
					dispatch('updateSocketLog', {content: '连接错误 onError='+JSON.stringify(err), status:2});
					
					state.IsOpen = false;
					state.SocketTask = false;
					
					$Http({
						url: 'imqddebug',
						data: {
							type: '连接错误',
							data: state.user?JSON.stringify(state.user):'',
							debugPt: uni.getSystemInfoSync().platform,
							debug: uni.getStorageSync('userInfo'),
							log: (typeof err == 'object')?JSON.stringify(err):(err||''),
						},
						type:'POST',
						load: false,
						noForceLogin: true,
					})
					
					if(state.heartbeatInterval != null){
						clearInterval(state.heartbeatInterval)
						state.heartbeatInterval = null
					}
					
					uni.$emit('onImStatus',{
						action: '监听错误',
						code: 'onError',
						IsOpen: state.IsOpen,
						SocketTask: state.SocketTask,
						IsOnline: state.IsOnline,
					});
					
					// 断线重连, 3秒重连一次
					state.timeoutObj = setTimeout(function() {
						dispatch('openSocket');
					}, 3000);
					
					if(!state.IsOnline){ //用户未登陆
						// if(state.timeoutObj){
						// 	clearTimeout(state.timeoutObj)
						// 	state.timeoutObj = null
						// }

						dispatch('clearLogin')
					}
				})
				// 监听接收信息
				state.SocketTask.onMessage((e)=>{
					console.debug('接收消息',e);
					try{
						// 字符串转json
						let res = JSON.parse(e.data);
						console.debug('接收消息Json',res);
						switch(res.type){
							case 'pong':
								console.log('心跳反馈')
							break;
							case 'offline': // 掉线/未登录返回客户端ID
								console.debug('clientId',res.data);
								dispatch('userBind')
							break;
							case 'connect': // 连接成功返回客户端ID
								console.debug('clientId',res.data);
								state.emojiData = res.data.emojiData
								dispatch('userBind')
							break;
							case 'bind': // 绑定用户反馈
								console.debug('clientId',res.data);
								// 改为上线状态
								state.IsOnline = true
								
								uni.$emit('onImStatus',{
									action: '绑定用户反馈',
									code: 'bind',
									IsOpen: state.IsOpen,
									SocketTask: state.SocketTask,
									IsOnline: state.IsOnline,
								});
								
								// 初始化会话列表
								dispatch('initChatList', res.data)
								// 获取未读信息
								dispatch('getUnreadMessages')
							break;
							case 'chat': // 会话
								// 处理接收消息
								dispatch('handleChatMessage',res.data)
							break;
						}
					} catch(e) {
		                console.debug('接收消息error: ', e);
		            }
				})
			},
			// 开启心跳检测
			startHeartbeat({state,dispatch}){
				if(state.heartbeatInterval != null){
					clearInterval(state.heartbeatInterval)
					state.heartbeatInterval = null
				}
				
				state.heartbeatInterval = setInterval(() => {
					dispatch('updateSocketLog', {content: '心跳检测'});
					
					state.SocketTask.send({
						data: JSON.stringify({
							type: 'ping',
							data: state.user,
							debugPt: uni.getSystemInfoSync().platform,
							debug: uni.getStorageSync('userInfo')
						})
					});
				}, 10000)
			},
			// 关闭socket √
			closeSocket({state,dispatch}){
				if (state.IsOpen){
					state.IsOnline = false;
					
					uni.$emit('onImStatus',{
						action: '关闭socket',
						code: 'closeSocket',
						IsOpen: state.IsOpen,
						SocketTask: state.SocketTask,
						IsOnline: state.IsOnline,
					});
					state.SocketTask.close();
				}
			},
			// 退出登录 √
			logout({state,dispatch}){
				state.IsOnline = false;
				
				uni.$emit('onImStatus',{
					action: '退出登录',
					code: 'logout',
					IsOpen: state.IsOpen,
					SocketTask: state.SocketTask,
					IsOnline: state.IsOnline,
				});
				
				// 清空登录状态信息
				dispatch('clearLogin')
			},
			clearLogin({state,dispatch}){
				state.user = {
					prefix: "HZ",
					uid: 0,
					nick: "",
					avatar: "",
				}
				state.userDoc = {
					prefix: "DT",
					uid: 0,
					nick: "",
					avatar: "",
				}
				
				state.FromUser = {
					prefix: "",
					uid: 0,
					nick: "",
					avatar: ""
				}
				state.ToUser = {
					prefix: "",
					uid: 0,
					nick: "",
					avatar: ""
				}
				// 清空会话列表
				dispatch('initChatList', {chatList:[], chatDocList:[]})
			},
//
			// 用户绑定 √
			userBind({state,dispatch}){
				// uni.clearStorage();
				$Http({
					url: 'getimUserInfo',
					data: {},
					type:'POST',
					load: false,
					noForceLogin: true,
				}).then(res => {
					console.log('getUserInfo: ', res, state)
					if (res.code == 1) { // 已登录
						state.user = {
							prefix: "HZ",
							uid: res.data.id,
							nick: res.data.nickname,
							avatar: res.data.headimgurl,
						}
						if(res.data.doctor_info){
							state.userDoc = {
								prefix: "DT",
								uid: res.data.id,
								nick: res.data.doctor_info?res.data.doctor_info.name:res.data.nickname,
								avatar: res.data.doctor_info?state.http_img + res.data.doctor_info.img:res.data.headimgurl,
							}
						}else{
							state.userDoc = {
								prefix: "DT",
								uid: 0,
								nick: "",
								avatar: "",
							}
						}
						
						state.SocketTask.send({
							data: JSON.stringify({
								type: 'bind',
								data: res.data.id,
							})
						});
					}else if (res.code == 101 || res.code == 102){ // 未登录/登录已过期，关闭连接
						dispatch('logout')
					}else{
						console.log('userBind: ', '获取用户信息失败')
						dispatch('logout')
					}
				});
			},

			// 初始化会话列表 -- 用户端/医生端 √
			async initChatList({state,dispatch,commit}, e){
				console.log('初始化用户端会话列表',state.chatList);
				var chatList = [], client = 'chatlist'
				e.chatList.forEach(msg=>{
					try {
						let message = JSON.parse(msg.message)['msg'];

						chatList.push({
							cate: msg.cate, //问诊类型 图文问诊[text] 视频问诊[video]
							orderno: msg.orderno, //问诊订单号
							uid: msg.uid, //对方ID
							nick: msg.nick, //对方昵称
							avatar: state.http_img + msg.avatar, //对方头像
							content: message.content, //最新消息
							note: $U.__formatChat(message), //最新消息格式化
							noread: parseInt(msg.noread), // 未读数

							update_time: message.time, // 最新消息时间戳
							_time: $U.__formatTime(message.time, true), //最新消息格式化时间
						})
					} catch(e) {}
				})
				commit('saveChatList',{chatList,client})

				console.log('初始化医生端会话列表',state.chatDocList);
				chatList = [], client = 'chatdoclist'
				e.chatDocList.forEach(msg=>{
					try {
						let message = JSON.parse(msg.message)['msg'];

						chatList.push({
							cate: msg.cate, //问诊类型 图文问诊[text] 视频问诊[video]
							orderno: msg.orderno, //问诊订单号
							uid: msg.uid, //对方ID
							nick: msg.nick, //对方昵称
							avatar: msg.avatar, //对方头像
							content: message.content, //最新消息
							note: $U.__formatChat(message), //最新消息格式化
							noread: parseInt(msg.noread), // 未读数

							update_time: message.time, // 最新消息时间戳
							_time: $U.__formatTime(message.time, true), //最新消息格式化时间
						})
					} catch(e) {}
				})
				commit('saveChatList',{chatList,client})


				state.chatList = await dispatch('getChatList')
				state.chatDocList = await dispatch('getChatList', 'chatdoclist')
				uni.$emit('onUpdateChatList',state.chatList);
				uni.$emit('onUpdateDocChatList',state.chatDocList);
				dispatch('updateTabbarBadge')
			},

		// 获取
			// 获取所有用户端聊天会话列表 -- 用户端/医生端 √
			getChatList({state}, client){
				var client = client || 'chatlist'
				let list = uni.getStorageSync(client+'_'+state.user.uid);
				return list ? JSON.parse(list) : []
			},

			// 获取未读信息 -- 用户端/医生端 ×
			getUnreadMessages({state,dispatch}){
				console.log('获取未读信息中...');
				// $http.post('/chat/get',{},{
				// 	token:true,
				// }).then((data)=>{
				// 	console.log('获取未读信息成功',data);
				// 	data.forEach(msg=>{
				// 		// 处理接收消息
				// 		dispatch('handleChatMessage',msg)
				// 	})
				// });
			},
		//
		
		// 处理
			// 处理接收消息 √-
			handleChatMessage({state,dispatch},data){
				console.log('处理接收消息',data);
				data.fromType = data.fromType || 'user'
				var fromType = data.fromType
				// 全局通知接口
				uni.$emit('UserChat',data);
				// 更新会话列表
				if(fromType=='user' && data.type!='consultationHandle'){
					dispatch('updateChatList',{
						data,
						send:false
					})
				}
				// 存储到chatdetail
				// dispatch('updateChatDetailToUser',{
				// 	data,
				// 	send:false
				// })
			},

			// 发送消息 √-
			async sendChatMessage({state, dispatch},data){
				console.log('发送消息',data);
				// 组织发送消息格式
				let sendData = await dispatch('formatSendData',data)
				console.log('发送消息数据格式',sendData);
				// 更新会话列表
				if(
					sendData.data.from.uid!=sendData.data.to.uid
					&& sendData.data.type!='consultationHandle'
				){
					// console.log('自发消息插入')
					uni.$emit('UserChat',sendData.data);
					dispatch('updateChatList',{
						data: sendData.data,
						send: true
					})
				}
				state.SocketTask.send({
					data: JSON.stringify(sendData)
				})
				// 更新与某个用户的消息历史记录
				// dispatch('updateChatDetailToUser',{
				// 	data:sendData,
				// 	send:true
				// })
				return sendData
			},

			// 读取当前会话(去除未读数,更新tabbar) √
			readChatMessage({state,commit,dispatch},item){
				console.log('读取当前会话(去除未读数,更新tabbar)',item);
				// 没有未读信息
				if (item.noread === 0) return;

				state.SocketTask.send({
					data: JSON.stringify({
							type: 'chatRead',
							data: {
								cate: item.cate,
								orderno: item.orderno,
								from: state.FromUser,
								to: state.ToUser,
							}
						})
				})

				var client = 'chatlist'
				var chatList = state.chatList
				if(item.isDoc){
					client = 'chatdoclist'
					chatList = state.chatDocList
				}
				// 拿到当前会话 设置未读数为0
				chatList.forEach((v)=>{
					console.debug('去除未读数',item,v,v.uid+v.cate+v.orderno, item.uid+item.cate+item.orderno);
					if(v.uid+v.cate+v.orderno == item.uid+item.cate+item.orderno){
						v.noread = 0
						console.log('去除未读数',v.nick)
					}
				})

				// 存储到本地存储
				if(item.isDoc){
					state.chatDocList = chatList
				}else{
					state.chatList = chatList
				}
				// 存储
				commit('saveChatList',{chatList,client})
				// 更新未读数
				dispatch('updateTabbarBadge')
			},
		//

		// 更新
			// 更新未读数 √
			updateTabbarBadge({state,getters}){
				let total = getters.totalNoread
				let totalDoc = getters.totalNoreadDoc
				console.log('更新未读数',total);
				console.log('更新医生端未读数',totalDoc);
				// total = Math.floor(Math.random() *10+1)
				// totalDoc = Math.floor(Math.random() *10+1)
				// 未读数为0,移除
				/*if(total === 0){
					console.log('移除未读数');
					return uni.removeTabBarBadge({
						index:2
					})
				}
				console.log('设置未读数',total);
				uni.setTabBarBadge({
					index:2,
					text: total > 99 ? '99+' : total.toString()
				});*/

				// 全局通知接口
				// 用户端
				uni.$emit('ComTabBarSetTabBarBadge', {
					index: 2,
					text: total,
				});
				// 医生端
				uni.$emit('ComTabBarDocSetTabBarBadge', {
					index: 1,
					text: totalDoc,
				});
			},

			// 更新聊天会话列表 √
			async updateChatList({state,dispatch,commit},{data,send}){
				console.log('更新聊天会话列表',data);
				// 是否是本人发送
				let isMySend = send
				console.log(isMySend ? '本人发送的信息' : '不是本人发送的');

				let isDoc = false
				let client = 'chatlist'
				try{
					if(data.from.uid==data.to.uid){ //同一个账号，判断是不是本人发送没有意义
					console.log('*********<<','同一个账号')
						// 接收端
						isMySend = send = false
						if(data.to.prefix=="DT"){
							isDoc = true
							client = 'chatdoclist'
						}else{
							isDoc = false
							client = 'chatlist'
						}
						await dispatch('updateChatListDo', {data,send,isMySend,isDoc,client})
					
						// 发送端
						isMySend = send = true
						if(data.from.prefix=="DT"){
							isDoc = true
							client = 'chatdoclist'
						}else{
							isDoc = false
							client = 'chatlist'
						}
						await dispatch('updateChatListDo', {data,send,isMySend,isDoc,client})
					}else{
						console.log('*********<<','不同账号')
						// 判断是更新用户端还是医生端
						if(isMySend){ //本人发送的信息
							if(data.from.prefix=="DT"){
								isDoc = true
								client = 'chatdoclist'
							}
						}else{ //不是本人发送的
							// if(data.to.prefix=="DT"){
							// 	isDoc = true
							// 	client = 'chatdoclist'
							// }
							
							if(data.from.uid==state.user.uid){
								isMySend = send = true
								if(data.from.prefix=="DT"){
									isDoc = true
									client = 'chatdoclist'
								}
							}else if(data.to.uid==state.user.uid){
								if(data.to.prefix=="DT"){
									isDoc = true
									client = 'chatdoclist'
								}
							}
						}
						
						await dispatch('updateChatListDo', {data,send,isMySend,isDoc,client})
					}
				} catch(e) {
	                console.log('接收消息error: ', e);
	            }
			},
			async updateChatListDo({state,dispatch,commit},e){
				console.log("当前是:", isDoc ? '医生端' : '用户端');
				var data = e.data,send=e.send,isMySend=e.isMySend,isDoc=e.isDoc,client=e.client
				// 获取之前会话
				let chatList = await dispatch('getChatList', client)
				// 判断是否已存在该会话，存在：将当前会话置顶；不存在：创建并追加至头部
				let i = chatList.findIndex((v)=>{
					var item = (isDoc?'HZ':'DT')+v.uid+v.cate+v.orderno
					console.log('*********<<', v, item, data.to.prefix+data.to.uid+data.cate+data.orderno, data.from.prefix+data.from.uid+data.cate+data.orderno)
					return item == data.to.prefix+data.to.uid+data.cate+data.orderno || item == data.from.prefix+data.from.uid+data.cate+data.orderno;
				})
				// 不存在,创建会话
				if(i === -1){
					let noread = isMySend?0:1 // 不是本人发送的，则未读数为1
					// 接收到的消息转会话
					let obj = await dispatch('formatChatListObject',{
						data,
						send,
						noread
					})
					console.log('不存在当前会话,创建',obj);
					// 追加头部
					chatList.unshift(obj);
				} else {
					// 存在：将当前会话置顶,修改当前会话的data和time显示
					let noread = chatList[i].noread
					// 当前聊天对象不是该id，未读数+1（排除本人发送消息）
					if(!isMySend && state.ToUser.prefix+state.ToUser.uid+data.cate+data.orderno !== (isDoc?'HZ':'DT')+chatList[i].uid+data.cate+data.orderno){
						noread++
					}
					// 接收到的消息转会话
					chatList[i] = await dispatch('formatChatListObject',{
						data,
						send,
						noread
					})
				
					console.log('存在当前会话',chatList[i]); 
					// 置顶当前会话
					chatList = $U.__toFirst(chatList,i)
				}
				// 存储到本地存储
				if(isDoc){
					state.chatDocList = chatList
					uni.$emit('onUpdateDocChatList',chatList);
				}else{
					state.chatList = chatList
					uni.$emit('onUpdateChatList',chatList);
				}
				commit('saveChatList',{chatList,client})
				// 不处于聊天当中,更新未读数
				console.log('updateTabbarBadge', data.orderno)
				// if(data.from.uid !== state.ToUser.uid && !isMySend){
				if(data.orderno !== state.chatOrderno && !isMySend){
					await dispatch('updateTabbarBadge')
				}
			},
		//
		
		// 格式化
			// 消息转聊天会话对象 √
			formatChatListObject({state},{data,send,noread}){
				var uid = send ? state.ToUser.uid : data.from.uid //对方ID
				var nick = send ? state.ToUser.nick : data.from.nick //对方昵称
				var avatar = send ? state.ToUser.avatar : data.from.avatar //对方头像
				if(!uid){
					uid = send ? data.to.uid : data.from.uid //对方ID
					nick = send ? data.to.nick : data.from.nick //对方昵称
					avatar = send ? data.to.avatar : data.from.avatar //对方头像
				}
				// 接收消息
				return {
					cate: data.cate, //问诊类型 图文问诊[text] 视频问诊[video]
					orderno: data.orderno, //问诊订单号
					uid: uid, //对方ID
					nick: nick, //对方昵称
					avatar: avatar, //对方头像
					content: data.content, //最新消息
					note: $U.__formatChat(data), //最新消息格式化
					noread: noread || 0, // 未读数

					update_time: data.time, // 最新消息时间戳
					_time: $U.__formatTime(data.time, true), //最新消息格式化时间
				}
			},

			// 组织发送格式 √
			formatSendData({state},e){
				return {
					type: 'chat',
					data: {
						cate: e.cate,
						orderno: e.orderno,
						fromType: 'user',
						from: state.FromUser,
						to: state.ToUser,
						type: e.type,
						content: e.content,
						time: Date.parse(new Date())/1000//new Date().getTime()
					}
				}
			},
		//
//
			// UserChat //全局通知接口
			// formatChatDetailObject

			// 更新与某个用户聊天内容列表
			async updateChatDetailToUser({state,dispatch,commit},e){
				console.log('更新与某个用户聊天内容列表',e);
				let data = e.data
				let toId = e.send ? state.ToUser.user_id : data.from_id
				// 获取与某个用户聊天内容的历史记录
				let list = await dispatch('getChatDetailToUser',toId)
				list.push(await dispatch('formatChatDetailObject',e))
				// 存储到本地存储
				commit('saveChatDetail',{
					list,toId
				})
			},

			// 获取与某个用户聊天内容列表
			getChatDetailToUser({state},toId = 0){
				// chatdetail_[当前用户id]_[聊天对象id]
				let myId = state.user.id
				toId = toId ? toId : state.ToUser.user_id
				let key = 'chatdetail_'+myId+'_'+toId
				let list = uni.getStorageSync(key)
				return list ? JSON.parse(list) : []
			},

			// 存储与某个用户聊天内容列表
			saveChatDetail(state,{list,toId}){
				// chatdetail_[当前用户id]_[聊天对象id]
				let myId = state.user.id
				toId = toId ? toId : state.ToUser.user_id
				let key = 'chatdetail_'+myId+'_'+toId
				uni.setStorageSync(key,JSON.stringify(list))
			},

			async updateSocketLog({state,dispatch,commit},{content, status}){
				let list = uni.getStorageSync('socketLog');
				list = list ? JSON.parse(list) : []
				list.unshift({
					time: uni.$u.timeFormat(parseInt(new Date().getTime()/1000), 'yyyy/mm/dd hh:MM:ss'),
					status: status||0,
					content: content,
				})
				uni.setStorageSync('socketLog', JSON.stringify(list))
			}
		/** ------ im end ------ */
	},
	getters: {
		/** ------ im ------ */
			// 总未读数 √
			totalNoread(state){
				let total = 0
				state.chatList.forEach(item=>{
					total += item.noread
				})
				return total
			},
			// 医生端 √
			totalNoreadDoc(state){
				let total = 0
				state.chatDocList.forEach(item=>{
					total += item.noread
				})
				return total
			}
		/** ------ im end ------ */
	},
})
export default store
